import numpy as np
import serial
import time
from serial import Serial
import matplotlib.pyplot as plt

SerMonitor = Serial(port="COM17",
                    baudrate=115200,
                    parity=serial.PARITY_NONE,
                    bytesize=8,
                    stopbits=1,
                    timeout=1)

SerCodeMachine = Serial(port="COM16",
                        baudrate=115200,
                        parity=serial.PARITY_NONE,
                        bytesize=8,
                        stopbits=1,
                        timeout=1)


def CODE2ZERO():
	code_SV = SerCodeMachine.readline()  # 读取串口一行的数据
	SV = code_SV.decode('UTF-8')  # 字节转换为字符串

	code_VV = SerCodeMachine.readline()  # 读取串口一行的数据
	VV = code_VV.decode('UTF-8')  # 字节转换为字符串

	code_sv = int(SV[3:-2])
	code_vv = int(VV[3:-2])

	x = b'\x01\x06\x00\x08\x00\x01\xC9\xC8\r\n'
	SerCodeMachine.write(x)
	print(SerCodeMachine.readline())
	print(SerCodeMachine.readline())
	print(SerCodeMachine.readline())

	monitor_T_command = str('T') + str('\r\n')
	monitor_F_command = str('F') + str('\r\n')

	if code_vv != 0:
		code2zero_command = 'function:ResetZeroPos.;'
		SerCodeMachine.write(code2zero_command)


	while code_sv != 0:
		if code_sv >= 0:
			cha = 1024 - code_sv
			if cha > 1000:
				SerMonitor.write(monitor_F_command.encode())
				time.sleep(1)
			else:
				SerMonitor.write(monitor_T_command.encode())
				time.sleep(1)

		else:
			SerMonitor.write(monitor_F_command.encode())
			time.sleep(1)
		if code_vv != 0:
			SerMonitor.write(monitor_F_command.encode())
			time.sleep(1)



def CODE_RUN():
	codemachine_receive_SV_list = []  # 单圈数值列表
	codemachine_receive_VV_list = []  # 多圈数值列表
	codemachine_receive_COIL_list = []  # 圈数

	code_SV = SerCodeMachine.readline()  # 读取串口一行的数据
	code_VV = SerCodeMachine.readline()  # 读取串口一行的数据

	SV = code_SV.decode('UTF-8')  # 字节转换为字符串
	codemachine_receive_SV_list.append(SV[3:-2])
	VV = code_VV.decode('UTF-8')  # 字节转换为字符串
	codemachine_receive_VV_list.append(VV[3:-2])

	code_CO = SerCodeMachine.readline()  # 读取串口一行的数据
	CO = code_CO.decode('UTF-8')  # 字节转换为字符串
	codemachine_receive_COIL_list.append(CO[3:-2])

	monitor_step_command = str(5) + str('\r\n')  # 转动
	monitor_T_command = str('T') + str('\r\n')  # 微调(正向)
	monitor_F_command = str('F') + str('\r\n')  # 微调（反向）

	# 转动
	SerMonitor.write(monitor_T_command.encode())
	time.sleep(0.1)
	# VV差值 #
	# 1.先读取VV值
	SerCodeMachine.readline()
	code_VV2 = SerCodeMachine.readline()  # 读取串口一行的数据
	VV2 = code_VV2.decode('UTF-8')  # 字节转换为字符串
	VV2 = int(VV2[3:-2])
	# 2.做差
	Difference_list = []
	Difference = VV2 - int(codemachine_receive_VV_list.pop())
	# 3.放进列表备用
	Difference_list.append(Difference)

	# 矫正多圈数值
	'''
    step_vv = 0
    for i in range(3):
        SETZEOR = SerCodeMachine.readline()  # 读取串口一行的数据
        SETZEOR_DECODE = SETZEOR.decode('UTF-8')  # 字节转换为字符串
        if SETZEOR_DECODE[0:2] == 'VV':
            step_vv= int(SETZEOR_DECODE[3:-2])

    forward_vv = int(codemachine_receive_VV_list.pop())
    '''

	# 微调
	'''
    while ((step_vv - forward_vv) != 17) :
        if step_vv - forward_vv > 17 :
            SerMonitor.write(monitor_F_command.encode())
            time.sleep(1)
        elif step_vv - forward_vv < 17 :
            SerMonitor.write(monitor_T_command.encode())
            time.sleep(1)

        else :
            pass
    else :
        pass


        # monitor_command_list = []
        #
        # list_set = (i + 1) * 5
        # monitor_command_list.append(list_set)



        # print(monitor_command_list)

        # for i in range (360) :
        #
        #     monitor_command = str(1) + str('\r\n')
        #     SerMonitor.write(monitor_command.encode())
        #
        #     monitor_command_list = []
        #
        #     list_set = (i + 1) * 5
        #     monitor_command_list.append(list_set)
        #     # print(monitor_command_list)
        #
        #
        #     SETZEOR = SerCodeMachine.readline()
        #     SETZEOR_DECODE = SETZEOR.decode('UTF-8')

        #     CODE_NUM = SETZEOR_DECODE[:-3]
        #     CODE_COIL = SETZEOR_DECODE[-3]

        #     # CHART = SerCodeMachine.readline()
        #     # CHART_DECODE = CHART.decode('UTF-8')

        #     time.sleep(1)
        #     # print(codemachine_receive_VV_list)
        #
        #     print("完成:", i+1, "次")
        #
        #
        # fig1 = plt.figure(figsize=(6, 6))
        # len_monitor = len(monitor_command_list)
        # x_monitor = np.arange(0, len_monitor)
        #
        # plt.plot(x_monitor, monitor_command_list)
        #
        # fig2 = plt.figure(figsize=(6, 6))
        # len_VVCode = len(codemachine_receive_VV_list)
        # x_code = np.arange(0, len_VVCode)
        #
        # plt.plot(x_code, codemachine_receive_VV_list)
        #
        #
        # fig3 = plt.figure(figsize=(6, 6))
        # plt.plot(x_monitor, monitor_command_list)
        # plt.plot(x_code, codemachine_receive_VV_list)
        #
        #
        # print(codemachine_receive_COIL_list[-1])
        #
        # plt.show()
    '''

	return Difference_list


if __name__ == '__main__':
	# CODE2ZERO()
	t1 = time.time()
	x = 0
	for i in range(2880):
		x = CODE_RUN()
	t2 = time.time()

	print(t2 - t1)
